<!-- 用户数据展示页面 -->
<template>
  <div class="content">
    <el-table
      id="rebateSetTable"
      ref="userTable"
      v-loading="isLoading"
      height="795"
      :data="userData"
      border
      @selection-change="handleSelectionChange"
      @cell-click="handleCellClick"
    >
      <el-table-column
        align="center"
        type="selection"
        width="49"
      />
      <el-table-column
        align="center"
        prop="id"
        label="序号"
        width="54"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="code"
        label="工号"
        width="94"
      />
      <el-table-column
        align="center"
        prop="name"
        label="用户名"
        width="94"
      />
      <el-table-column
        align="center"
        prop="company.name"
        label="所属公司"
        width="104"
      />
      <el-table-column
        align="center"
        prop="department.name"
        label="所属部门"
        width="94"
      />
      <el-table-column
        align="center"
        prop="roleList"
        label="所属角色"
        width="124"
      >
        <template slot-scope="scope">
          <span
            v-for="item in scope.row.roleList"
            :key="item.id"
            style="cursor:pointer"
          >
            {{ item.name }}&nbsp;
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="position.name"
        label="职位"
        width="94"
      />
      <el-table-column
        align="center"
        prop="sex"
        label="性别"
        width="54"
        :formatter="(row, column) => row.sex === 0 ? '男' : '女'"
      />
      <el-table-column
        align="center"
        sortable
        prop="birthday"
        label="生日"
        width="154"
      >
        <template slot-scope="scope">
          <div v-if="!scope.row.birthday">/</div>
          <div v-else>{{ getBirthday(scope.row.birthday) }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="tel"
        label="电话"
        width="124"
      />
      <el-table-column
        align="center"
        prop="status"
        label="状态"
        width="99"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 3" type="success">启用</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="right"
        prop="operation"
        label="操作"
        width="299"
      >
        <template slot-scope="scope">
          <el-button
            id="btnCopy"
            type="primary"
            size="mini"
            @click="copyUser(scope.$index, scope.row)"
          >复制</el-button>
          <el-button
            id="btnUpdateUser1"
            size="mini"
            @click="editUser(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            id="btnDeleteUser1"
            type="danger"
            size="mini"
            @click="deleteUser(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="paginationData.pageCount"
      :page-size="paginationData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paginationData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import {
  commonQuery,
  remove
} from '@/api/right/user'

export default {
  name: 'Table',
  data() {
    return {
      // 用户信息
      userData: [],
      // 被选中的用户信息
      userDataSelection: [],
      // 当前页选中的用户信息
      currentUserDataSelection: [],
      // 被选中的用户信息表 用于跨页
      userDataSelectionForm: [],
      // 查询用户信息接口字段
      userQuery: {
        name: '',
        code: '',
        tel: '',
        roleId: '',
        departmentId: '',
        positionId: '',
        // 类似于limit
        pageSize: 10,
        // 类似于offset
        pageNum: 1
      },
      // 分页信息
      paginationData: {
        // 当前页面序号，默认为1
        pageCount: 1,
        // 每页数据数
        pageSize: 10,
        // 总共数据数
        total: 0
      },
      // 是否处于加载状态
      isLoading: false
    }
  },
  mounted() {
    this.getUser(this.userQuery)
    this.$nextTick(function() {
      /**
       * 对用户数据操作后重新获取用户信息
       */
      this.$on('getUser', function() {
        this.getUser(this.userQuery)
      })
      /**
       * 搜索用户
       */
      this.$on('searchUser', async(data) => {
        const { name, code, tel, roleId, departmentId, positionId } = data
        this.userQuery = {
          name,
          code,
          tel,
          roleId,
          departmentId,
          positionId,
          pageSize: 10,
          pageNum: 1
        }
        this.getUser(this.userQuery)
      })
      /**
       * 提供分页信息
       */
      this.$on('getPaginationData', () => {
        return this.paginationData
      })
    })
  },
  methods: {
    /**
     * 更改被选中数据的数组
     * @param {*} val 被选中的数据
     */
    handleSelectionChange(val) {
      // 更新选中的数据
      val.forEach(item => {
        if (!this.currentUserDataSelection.includes(item)) {
          this.userDataSelection.push(item)
        }
      })
      this.currentUserDataSelection.forEach(item => {
        if (!val.includes(item)) {
          const index = this.userDataSelection.findIndex(v => v === item)
          this.userDataSelection.splice(index, 1)
        }
      })

      this.currentUserDataSelection = val
    },
    /**
     * 获取用户数据
     * @param {*} userQuery 用户信息
     */
    async getUser(userQuery) {
      this.isLoading = true
      try {
        let res = await commonQuery(userQuery)
        const { total, data } = res
        // 更改总数据数
        this.paginationData.total = parseInt(total)
        // 获取查询的数据
        this.userData = data

        // 若本页有数据被选中，则选中
        this.$nextTick(() => {
          if (this.userDataSelectionForm[this.paginationData.pageCount - 1]) {
            const rows = this.userDataSelectionForm[this.paginationData.pageCount - 1]
            rows.forEach(row => {
              this.userData.map(item => {
                if (item.code === row.code) {
                  this.$refs.userTable.toggleRowSelection(item, true)
                }
              })
            })
          }
        })
      } catch (e) {
        this.$message.error(e)
      } finally {
        this.isLoading = false
      }
    },
    /**
     * 复制用户
     * @param {*} index 用户序号
     * @param {*} row 用户数据
     */
    copyUser(index, row) {
      this.$emit('copyUser', row)
    },
    /**
     * 编辑用户
     * @param {*} index 用户序号
     * @param {*} row 用户数据
     */
    editUser(index, row) {
      this.$emit('editUser', row)
    },
    /**
     * 删除用户数据
     * @param {*} index 用户序号
     * @param {*} row 用户数据d
     */
    deleteUser(index, row) {
      this.$confirm('确定要删除吗？')
        .then(async() => {
          try {
            let res = await remove(this.userData[index].id, this.userData[index].version)
            if (res) {
              this.$message.success('用户删除成功')
              this.$emit('operateUserSuccess')
            } else {
              this.$message.error('用户删除失败')
            }
          } catch {
            this.$message.error('网络错误')
          }
        })
        .catch(req => {})
    },
    /**
     * 当某单元格被点击
     * @param {*} row
     * @param {*} column
     * @param {*} cell
     * @param {*} event
     */
    handleCellClick(row, column, cell, event) {
      if (column.label === '所属角色') {
        this.$emit('viewResource', row)
      }
    },
    /**
     * 更改页面尺寸时重新获取数据
     * @param {*} val
     */
    handleSizeChange(val) {
      this.userDataSelectionForm = []
      this.userDataSelection = []
      this.currentUserDataSelection = []
      this.paginationData.pageSize = val
      this.userQuery.pageSize = val
      this.getUser(this.userQuery)
    },
    /**
     * 当前页面发生变化时重新获取数据
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.userDataSelectionForm[this.userQuery.pageNum - 1] = this.currentUserDataSelection
      // 添加离去页的数据，防止遗漏
      if (this.currentUserDataSelection) {
        this.userDataSelection.push(...this.currentUserDataSelection)
      }
      // 删除到达页的数据，防止重复
      if (this.userDataSelectionForm[val - 1]) {
        this.userDataSelectionForm[val - 1].forEach(item => {
          const index = this.userDataSelection.findIndex(v => v === item)
          this.userDataSelection.splice(index, 1)
        })
      }

      this.paginationData.pageCount = val
      this.userQuery.pageNum = val
      this.getUser(this.userQuery)
    },

    /**
     * 得到生日
     * @param {*} date 日期
     */
    getBirthday(date) {
      return date.split('T')[0]
    }
  }
}
</script>

<style scoped>

</style>
